<template>
  <div class="waterfall-container">
    <div class="waterfall-column" ref="leftColumn">
      <ProductItem v-for="item in leftList" :item="item" :key="item.feed_id" />
    </div>
    <div class="waterfall-column" ref="rightColumn">
      <ProductItem v-for="item in rightList" :item="item" :key="item.feed_id" />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { useUserStore } from '@/store/user';
  import { FeedItem } from '@/api/feeds';
  import { computed, nextTick, ref, watch } from 'vue';
  import ProductItem from '@/components/ProductItem.vue';

  const router = useRouter();
  const userStore = useUserStore();
  interface Props {
    products: FeedItem[];
    loading?: boolean;
    loadMoreLoading?: boolean;
    hasMore?: boolean;
  }
  const isLoggedIn = computed(() => userStore.isAuthenticated);
  const userInfo = computed(() => userStore.user);

  const leftList = ref<FeedItem[]>([]);
  const rightList = ref<FeedItem[]>([]);
  const leftColumnHeight = ref(0);
  const rightColumnHeight = ref(0);

  const props = withDefaults(defineProps<Props>(), {
    products: () => [],
    loading: false,
    loadMoreLoading: false,
    hasMore: true,
  });

  watch(
    () => props.products,
    (newProducts, oldProducts) => {
      const oldLength = oldProducts?.length || 0;
      const newLength = newProducts?.length || 0;
      // 数据增加
      if (newLength > oldLength) {
        const list = newProducts.slice(oldLength, newLength - 1);
        assignImages(list);
        return;
      }
      // 数据减少，说明重置数据
      leftList.value = [];
      rightList.value = [];
      leftColumnHeight.value = 0;
      rightColumnHeight.value = 0;
      assignImages(newProducts);
    },
    { deep: true }
  );

  const assignImages = (data: any) => {
    if (!data.length) return;
    data.forEach((item: FeedItem) => {
      const leftHeight = leftColumnHeight.value;
      const rightHeight = rightColumnHeight.value;
      if (leftHeight <= rightHeight) {
        leftList.value.push(item);
        leftColumnHeight.value = leftColumnHeight.value + item.thumbnail?.height || 0;
      } else {
        rightList.value.push(item);
        rightColumnHeight.value = rightColumnHeight.value + item.thumbnail?.height || 0;
      }
    });
  };
</script>

<style scoped lang="scss">
  .waterfall-container {
    display: flex;
    flex-direction: row;
    gap: 8px;
  }
  .waterfall-column {
    flex: 1;
  }
</style>
